/*

  Shennong.ino

  Scroll through Chinese Short Story
  "The Farmer God Shen Nong Tastes All the Plants"

  U8g2_for_TFT_eSPI:
    - Use U8g2 fonts with TFT_eSPI
    - Support for UTF-8 in print statement
    - 90, 180 and 270 degree text direction

  List of all U8g2 fonts:    https://github.com/olikraus/u8g2/wiki/fntlistall

  TFT_eSPI library:          https://github.com/Bodmer/TFT_eSPI
  U8g2_for_TFT_eSPI library: https://github.com/Bodmer/U8g2_for_TFT_eSPI


  English translation:
  The Farmer God Shen Nong Tastes All the Plants

  Source:
  http://chinesereadingpractice.com/2012/08/22/the-farmer-god-shen-nong-tastes-all-the-plants/

  All his life, Shen Nong had a crystal abdomen, and one could
  clearly see all of his internal organs. At that time, humans were
  often getting sick and even dying because they ate things
  indiscriminately [not knowing if they were good or bad]. Shen
  Nong determinedly tasted everything everywhere; the
  good-tasting things he put in a bag on his left side, those were
  for people to eat; the bad-tasting things he put in a bag on his
  right side, and those were used for medicine.

  The first time, Shen Nong tasted a small fresh leaf. As this leaf
  fell into his stomach, it cleaned every inch of his insides so that
  every organ top and bottom was fresh and cool, as if [the leaf]
  was somehow on patrol [making the rounds], so Shen Nong
  called it “chá�? [to investigate / check], and later generations of
  men called it “chá�? [tea]. Shen Nong put it in the bag on the
  right. The second time, Shen Nong tasted a little light red flower
  that looked like a butterfly, which was sweet and delicious, with
  an exotic smell that filled his nostrils, so he called it “licorice�?. He
  put it in the bag on the left. In this way, Shen Nong diligently
  tasted all manner of flora, and every time he was poisoned, he
  used tea to rescue himself. Before long, the bag on his left
  contained 47,000 kinds of flowers, grasses, roots and leaves,
  and the right side had 398,000 kinds.

  But one day, Shen Nong tasted “heartbreak grass�?, and this
  poison was too terrible, so there wasn’t enough time to eat the
  tea leaves to detoxify and he died. He sacrificed himself to save
  humanity, so people call him the “Bodhisattva of Medicine�?, and
  people forever commemorate him through this story.


*/
// #include <stdint.h>
#include "SPI.h"
#include "TFT_eSPI.h"
#include <TimeLib.h>

#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClientSecureBearSSL.h>
#else
#include <WiFi.h>
#include <HTTPClient.h>
#endif

#include "WMHelper.h"
#include "TimeUtil.h"

TFT_eSPI tft = TFT_eSPI(); // tft instance
U8g2_for_TFT_eSPI u8f;     // U8g2 font instance

// To read the short story with all glyphs you need at least a font with _gb2312b postfix
// However, a font with _gb2312b postfix is very large and will not always fit on
// the target controller. For testing you can use _chinese1 extension, but then
// many glyphs are skipped and not visible.
//
// wqy fonts are available in different sizes, here are only wqy12, wqy14 and wqy16 listed

// #define FONT u8g2_font_wqy12_t_chinese1
#define FONT u8g2_font_wqy16_t_gb2312b

//#define FONT u8g2_font_wqy14_t_chinese1
//#define FONT u8g2_font_wqy14_t_gb2312b

//#define FONT u8g2_font_wqy16_t_chinese1
// #define FONT u8g2_font_wqy16_t_gb2312b

// The next two macros define the scroll speed of the short story
#define SCROLL_DELTA 4
#define SCROLL_DELAY 100

time_t prevDisplay = 0; // 显示时间
time_t weaterTime = 0;  // 显示天气

time_t getNtpTime();

long lastMqttConn = 0;
void checkNetStatus()
{
  // Wifi掉线重连
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWifi();
  }

  //非阻塞Mqtt重连，间隔30秒
  if (WiFi.status() == WL_CONNECTED)
  {
    long now = millis();
    if (!mqttClient.connected())
    {
      if (now - lastMqttConn > 30000)
      {
        lastMqttConn = now;
        connectMqtt();
      }
    }
    else
    {
      mqttClient.loop();
    }
  }
}

Weather weather;
Display display;

// This next function will be called during decoding of the jpeg file to
// render each block to the TFT.  If you use a different TFT library
// you will need to adapt this function to suit.
bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap)
{
  // Stop further decoding as image is running off bottom of screen
  if (y >= tft.height())
    return 0;

  // This function will clip the image block rendering automatically at the TFT boundaries
  tft.pushImage(x, y, w, h, bitmap);

  // This might work instead if you adapt the sketch to use the Adafruit_GFX library
  // tft.drawRGBBitmap(x, y, bitmap, w, h);

  // Return 1 to decode next block
  return 1;
}
/**
 *
 *图片解码初始化
 */
void setupJpg()
{
  // The jpeg image can be scaled by a factor of 1, 2, 4, or 8
  TJpgDec.setJpgScale(2);

  // The byte order can be swapped (set true for TFT_eSPI)
  TJpgDec.setSwapBytes(true);

  // The decoder must be given the exact name of the rendering function above
  TJpgDec.setCallback(tft_output);
}

void setup()
{
  tft.begin();
  tft.setRotation(0);
  tft.fillScreen(TFT_WHITE);
  u8f.begin(tft); // connect u8g2 procedures to TFT_eSPI
  u8f.setFont(FONT);
  u8f.setForegroundColor(TFT_BLACK); // apply color
  u8f.setBackgroundColor(TFT_WHITE); // apply color

  display.init(&tft, &u8f);
  Serial.begin(115200);
  //背景
  tft.fillRoundRect(0, 0, 128, 160, 5, TFT_WHITE);
  connectWifi();
  connectMqtt();

  setSyncProvider(getNtpTime);
  setSyncInterval(300);
  display.setUpClock();
  // publishNtp();
  // getTime();

  display.setupWeather(weather.getCityWeater());

  setupJpg();
  // initDisplay(&display);
  display.setUpText("HelloWorld");
}

void loop()
{
  display.imgAnim();
  display.textLoop();
  display.setUpClock();
  // delay(SCROLL_DELAY);

  checkNetStatus();

  if (now() != prevDisplay)
  {
    prevDisplay = now();
    // setUpClock();
  }
  if (millis() - weaterTime > 300000)
  { // 5分钟更新一次天气
    weaterTime = millis();
    display.setupWeather(weather.getCityWeater());
  }
}
